//
//  UserRoutes.swift
//  Application
//
//  Created by LevyGG on 2019/7/7.
//

import KituraContracts
import CouchDB
import LoggerAPI

func initializeUserRoutes(app: App) {
    app.router.post("/user", handler: app.userSaveHandler)
    app.router.get("/user", handler: app.userFindAllHandler)
}
extension App {
    
    func userSaveHandler(user: User, completion: @escaping (User?, RequestError?) -> Void) {
        // Save user here
        App.couchDBClient.retrieveDB("user") { (database, error) in
            guard let database = database  else {
                return completion(nil, .internalServerError)
            }
            // Initialize document here
            database.create(user) { (response, error) in
                guard let response = response else {
                    return completion(nil, RequestError(httpCode: error?.statusCode ?? 500))
                }
                var updatedUser = user
                updatedUser._id = response.id
                updatedUser._rev = response.rev
                completion(updatedUser, nil)
            }
        }
    }
    
    func userFindAllHandler(completion: @escaping ([User]?, RequestError?) -> Void) {
        App.couchDBClient.retrieveDB("user") { (database, error) in
            guard let database = database  else {
                return completion(nil, .internalServerError)
            }
            database.retrieveAll(includeDocuments: true, callback: { (allDocuments, error) in
                guard let allDocuments = allDocuments else {
                    return completion(nil, RequestError(httpCode: error?.statusCode ?? 500))
                }
                let users = allDocuments.decodeDocuments(ofType: User.self)
                completion(users, nil)
            })
        }
    }
}
